package com.chujiu.utils.sign;

import com.cj.framework.core.exception.ApplicationException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Hashtable;

@Component
public class SignVerifyHandle implements ISignVerify {

	private Hashtable<String, String[]> partnerKeyTable = new Hashtable<String, String[]>();
	
	public Hashtable<String, String[]> getPartnerKeyTable() {
		return partnerKeyTable;
	}

	public void setPartnerKeyTable(
			Hashtable<String, String[]> partnerKeyTable) {
		this.partnerKeyTable = partnerKeyTable;
	}
	/**
	 *vipNum:会员编号（合作平台编号）
	 *bizData:业务参数
	 */
	public String signData(String vipNum, String bizData) {
		//获取合作商务号对应的私钥信息
		String partnerKey = StringUtils.EMPTY;
		String priKeyContent = StringUtils.EMPTY;
		String pubKeyContent = StringUtils.EMPTY;

			//String[] keyInfos = partnerKeyTable.get(vipNum);
			String priKeyFile = "conf/cert/scdpartner.pri";//私钥文件
			String pubKeyFile = "conf/cert/scdpartner.pub";//公钥文件
			priKeyFile = CertSign.getSysPath() + priKeyFile;
			pubKeyFile = CertSign.getSysPath() + pubKeyFile;

			partnerKey = "N3cG91dJOQQ2cWLb";
			priKeyContent = CertSign.getKeyContent(priKeyFile);
			pubKeyContent = CertSign.getKeyContent(pubKeyFile);

		if (StringUtils.isBlank(priKeyContent) || StringUtils.isBlank(pubKeyContent)) {
			throw new ApplicationException("MSG_0009");
		}
		//获取摘要
		String summaryData = CertSign.getOriginSummary(vipNum + bizData + partnerKey);
		//进行签名
		String summarySign = CertSign.makeSign(priKeyContent, summaryData);
		return summarySign;
	}
	
	/**
	 *vipNum:会员编号（合作平台编号）
	 *bizData:业务参数
	 *signData:签名参数(对body加签)
	 */
	public boolean verifySign(String vipNum, String bizData, String signData) {
		//获取合作商务号对应的私钥信息
			String partnerKey = StringUtils.EMPTY;
			String priKeyContent = StringUtils.EMPTY;
			String pubKeyContent = StringUtils.EMPTY;
				String priKeyFile = "conf/cert/scdpartner.pri";//私钥文件
				String pubKeyFile = "conf/cert/scdpartner.pub";//公钥文件
				priKeyFile = CertSign.getSysPath() + priKeyFile;
				pubKeyFile = CertSign.getSysPath() + pubKeyFile;

				partnerKey = "1wJ3o#Hg#n1UBSNV";
				priKeyContent = CertSign.getKeyContent(priKeyFile);
				pubKeyContent = CertSign.getKeyContent(pubKeyFile);


			if (StringUtils.isBlank(priKeyContent) || StringUtils.isBlank(pubKeyContent)) {
				throw new ApplicationException("MSG_0009");
			}
			//获取摘要
			String summaryData = CertSign.getOriginSummary(vipNum + bizData + partnerKey);
			//验证签名
			boolean result = CertSign.verifySign(pubKeyContent, summaryData, signData);		
			return result;
		}
}
